package org.example.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.anno.Log;
import org.example.mapper.OperateLogMapper;
import org.example.pojo.OperateLog;
import org.example.utils.CurrentHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
public class OperationLogAspect{
    @Autowired
    private OperateLogMapper operationLogMapper;

    //环绕通知
    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint joinPoint, Log log) throws Throwable{
        //记录开始时间
        long beginTime = System.currentTimeMillis();
        //执行目标方法
        Object result = joinPoint.proceed();
        //记录结束时间
        long endTime = System.currentTimeMillis();
        //耗时
        long costTime = endTime - beginTime;

        //构建日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime(costTime);

        //插入操作日志
        operationLogMapper.insert(operateLog);
        return result;

    }

    private Integer getCurrentUserId(){
        return CurrentHolder.get();
    }
}
